package com.cens.mall.commodity.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cens.mall.commodity.service.CategoryBrandRelationService;
import com.cens.mall.commodity.vo.Catalog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cens.common.utils.PageUtils;
import com.cens.common.utils.Query;

import com.cens.mall.commodity.dao.CategoryDao;
import com.cens.mall.commodity.entity.CategoryEntity;
import com.cens.mall.commodity.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查询所有分类
        List<CategoryEntity> categories = baseMapper.selectList(new LambdaQueryWrapper<>());
        //2.维护树形结构
        return categories.stream()
                .filter(c -> c.getParentCid() == 0)
                .peek(c -> c.setChildren(getChilds(c, categories)))
                .sorted(Comparator.comparing(CategoryEntity::getSort))
                .collect(Collectors.toList());
    }

    @Override
    public void removeCategories(List<Long> asList) {
        baseMapper.deleteBatchIds(asList);

    }

    @Override
    public Long[] findCateLogPath(Long catelogId) {
        List<Long> path = findParentPath(catelogId, new ArrayList<>());
        return path.toArray(new Long[path.size()]);
    }

    @Override
    @Transactional
    //清除多个缓存
    @Caching(evict = {
            @CacheEvict(value = {"category"},key = "'getLevelOneCategorys'"),
            @CacheEvict(value = {"category"},key = "'catalog_json'")
    })
    //删除某个分区下的所有数据
//    @CacheEvict(value = {"category"},allEntries = true)
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        if (StringUtils.isNotEmpty(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }
    }

    @Override
    @Cacheable(value = {"category"}, key = "#root.method.name")
    public List<CategoryEntity> getLevelOneCategorys() {
        return this.baseMapper.selectList(
                new QueryWrapper<CategoryEntity>()
                        .eq("parent_cid", 0)
        );
    }

    private List<CategoryEntity> getByParentCid(List<CategoryEntity> categoryEntities, Long parentCid) {
        return categoryEntities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == parentCid)
                .collect(Collectors.toList());
    }

    @Override
    @Cacheable(value = {"category"},key = "'catalog_json'")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(null);

        List<CategoryEntity> levelOneCategorys = getByParentCid(categoryEntities, 0L);
        Map<String, List<Catalog2Vo>> result = levelOneCategorys.stream()
                .collect(
                        Collectors.toMap(
                                c -> c.getCatId().toString(),
                                c ->
                                        getByParentCid(categoryEntities, c.getCatId())
                                                .stream()
                                                .filter(Objects::nonNull)
                                                .map(
                                                        catalog2 ->
                                                                Catalog2Vo.builder()
                                                                        .catalog1Id(c.getCatId().toString())
                                                                        .id(catalog2.getCatId().toString())
                                                                        .name(catalog2.getName())
                                                                        .catalog3List(
                                                                                getByParentCid(categoryEntities, catalog2.getCatId())
                                                                                        .stream()
                                                                                        .filter(Objects::nonNull)
                                                                                        .map(
                                                                                                catalog3 ->
                                                                                                        Catalog2Vo.Catalog3Vo.builder()
                                                                                                                .catalog2Id(catalog2.getCatId().toString())
                                                                                                                .id(catalog3.getCatId().toString())
                                                                                                                .name(catalog3.getName())
                                                                                                                .build()
                                                                                        ).collect(Collectors.toList())
                                                                        )
                                                                        .build()
                                                ).collect(Collectors.toList())
                        )
                );
        return result;
    }

    private static final String CATALOG = "catalog_json";

    public Map<String, List<Catalog2Vo>> getCatalogJson2() {
        String result = redisTemplate.opsForValue()
                .get(CATALOG);
        if (StringUtils.isEmpty(result)) {
            Map<String, List<Catalog2Vo>> catalog = getCatalogJsonFromDBWithRedissonLock();
            return catalog;
        }
        return JSON.parseObject(result, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });
    }

    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDBWithRedissonLock() {
        RLock lock = redissonClient.getLock("catalogJson-lock");
        lock.lock();
        try {
            Map<String, List<Catalog2Vo>> data = getDataFromDB();
            return data;
        } finally {
            lock.unlock();
        }
    }

    private Map<String, List<Catalog2Vo>> getDataFromDB() {
        String redisResult = redisTemplate.opsForValue()
                .get(CATALOG);
        if (StringUtils.isNotEmpty(redisResult)) {
            return JSON.parseObject(redisResult, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            });
        }
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(null);

        List<CategoryEntity> levelOneCategorys = getByParentCid(categoryEntities, 0L);
        Map<String, List<Catalog2Vo>> result = levelOneCategorys.stream()
                .collect(
                        Collectors.toMap(
                                c -> c.getCatId().toString(),
                                c ->
                                        getByParentCid(categoryEntities, c.getCatId())
                                                .stream()
                                                .filter(Objects::nonNull)
                                                .map(
                                                        catalog2 ->
                                                                Catalog2Vo.builder()
                                                                        .catalog1Id(c.getCatId().toString())
                                                                        .id(catalog2.getCatId().toString())
                                                                        .name(catalog2.getName())
                                                                        .catalog3List(
                                                                                getByParentCid(categoryEntities, catalog2.getCatId())
                                                                                        .stream()
                                                                                        .filter(Objects::nonNull)
                                                                                        .map(
                                                                                                catalog3 ->
                                                                                                        Catalog2Vo.Catalog3Vo.builder()
                                                                                                                .catalog2Id(catalog2.getCatId().toString())
                                                                                                                .id(catalog3.getCatId().toString())
                                                                                                                .name(catalog3.getName())
                                                                                                                .build()
                                                                                        ).collect(Collectors.toList())
                                                                        )
                                                                        .build()
                                                ).collect(Collectors.toList())
                        )
                );
        redisTemplate.opsForValue().set(CATALOG, JSON.toJSONString(result), 1, TimeUnit.DAYS);
        return result;
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            findParentPath(categoryEntity.getParentCid(), paths);
        }
        paths.add(categoryEntity.getCatId());
        return paths;
    }

    private List<CategoryEntity> getChilds(CategoryEntity current, List<CategoryEntity> categoryEntities) {
        return categoryEntities.stream()
                .filter(c -> Objects.equals(c.getParentCid(), current.getCatId()))
                .peek(c -> c.setChildren(getChilds(c, categoryEntities)))
                .sorted(Comparator.comparing(CategoryEntity::getSort))
                .collect(Collectors.toList());
    }

}